//
//  CZPlaceholderTextView.swift
//  iOSWeibo10
//
//  Created by 李伟鹏 on 16/5/21.
//  Copyright © 2016年 itcast. All rights reserved.
//

import UIKit

class CZPlaceholderTextView: UITextView {

    
    /// 占位文本
    var placeholder: String? {
        didSet {
            // 别人设置文字.将文字设置给label
            placeholderLabel.text = placeholder
        }
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    override init(frame: CGRect, textContainer: NSTextContainer?) {
        super.init(frame: frame, textContainer: textContainer)
        
        prepareUI()
        
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "textDidChange", name: UITextViewTextDidChangeNotification, object: self)
    }
    
    deinit{
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    func textDidChange(){
        CZPrint(items: "使用通知监听到了textView文字的改变")
        placeholderLabel.hidden = self.hasText()
    }

    private func prepareUI(){
        self.addSubview(placeholderLabel)
        
        placeholderLabel.snp_makeConstraints { (make) -> Void in
            make.leading.equalTo(self).offset(5)
            make.top.equalTo(self).offset(8)
        }
    }
    
    private lazy var placeholderLabel: UILabel = {
        let label = UILabel()
        
        // 设置
        label.font = UIFont.systemFontOfSize(ComposeTextFontSize)
        label.textColor = UIColor.lightGrayColor()
        
        return label
    }()
}

extension CZPlaceholderTextView:UITextViewDelegate{
    func textViewDidChange(textView: UITextView) {
        placeholderLabel.hidden = textView.hasText()
    }
}
